<?php

namespace DebugComponent;

/**
 * Class Debug
 * Debug encapsulate debug platform
 *
 * @author Milan Hradil <milan.hradil@email.cz>
 * @version 1.0
 * @package DebugComponent
 */
class Debug {

    /**
     * Class constructor
     *
     * @param IRenderer $renderer renderer instance which ensure debug rendering
     * @return Debug instance
     */
    public function __construct(IRenderer $renderer) {
        $this->plugins = array();
        $this->renderer = $renderer;
    }

    /**
     * Add debug plugin
     *
     * @param IPlugin $plugin
     * @return void
     */
    public function addPlugin(IPlugin $plugin) {
        $this->plugins[] = $plugin;
    }

    /**
     * Dispatch debug message
     *
     * @param IMessage $message
     * @return void
     */
    public function dispatch(IMessage $message) {
        foreach ($this->plugins as $plugin) {
            if ($plugin instanceof IMessagePlugin) {
                foreach ($plugin->getListenMessages() as $messageType) {
                    if ($message instanceof $messageType) {
                        $plugin->write($message);
                        break;
                    }
                }
            }
        }
    }

    /**
     * Render debug
     *
     * @return string HTML code
     */
    public function render() {
        $parameterHolder = new ParameterHolder();
        $plugins = $this->plugins;
        foreach ($plugins as $index=>$plugin) {
            if (!$plugin instanceof IRenderable) {
                unset($plugins[$index]);
            }
        }
        $parameterHolder->set('plugins', $plugins);
        return $this->renderer->render($parameterHolder);
    }

    /**
     * @var array of plugins
     */
    private $plugins;

    /**
     * @var IRenderer debug renderer
     */
    private $renderer;
}
